package com.repro.baselib.lib_base.network.converterFactorys;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * 自定义解析器
 *
 * 根据方法参数,判断是否要处理,不处理的话,要返回null,以便retrofit能从ConverterFactory列表里取下一个Factory实例
 */
public class RetroConverterFactory extends  Converter.Factory{

    private final Gson gson;

    public RetroConverterFactory(Gson gson) {
        this.gson = gson;
    }

    public static RetroConverterFactory create(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        return new RetroConverterFactory(gson);
    }


    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new GsonResponseConverterFactory<>(gson,type,annotations);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return new GsonOnRequestConverterFactory<>(gson,gson.getAdapter(TypeToken.get(type)));
    }
}
